import { sendEmailCode } from "@/api/toolsApi";
import { ResponseCode } from "@/common/Responsetypes";
import { reactive, onBeforeUnmount } from "vue";
import validator from "validator";

export default function () {
  const emailCodeOptions = reactive({
    text: "获取验证码",
    disabled: false,
    s: 60,
  });

  const getCode = async (email: string) => {
    uni.showLoading();

    if (!validator.isEmail(email)) {
      uni.hideLoading();
      uni.showToast({
        title: "请输入正确的邮箱",
        icon: "none",
        mask: true,
      });
      return;
    }

    emailCodeOptions.disabled = true;
    const originTime = emailCodeOptions.s;
    emailCodeOptions.text = `(${originTime})重新获取`;

    const timer = setInterval(() => {
      if (emailCodeOptions.s === 0) {
        clearInterval(timer);
        emailCodeOptions.s = originTime;
        emailCodeOptions.disabled = false;
        emailCodeOptions.text = "获取验证码";
      } else {
        emailCodeOptions.s--;
        console.log("倒计时 " + emailCodeOptions.s);
        emailCodeOptions.text = `(${emailCodeOptions.s})重新获取`;
      }
    }, 1000);

    onBeforeUnmount(() => {
      clearInterval(timer);
    });

    const result = await sendEmailCode(email);
    if (result.code === ResponseCode.PASS) {
      uni.hideLoading();
      uni.showToast({
        title: "验证码发送成功",
        icon: "none",
        mask: true,
      });
    }
  };

  return {
    getCode,
    emailCodeOptions,
  };
}
